package com.free.mail;

import com.free.mail.model.Mail;
import com.free.mail.model.MailConfig;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * <p>
 * 功能概述:
 * </p>
 * <p>
 * 功能详述:
 * </p>
 */
public class MailUtils {


    public static MailConfigure getConfigure(String path)
    {
        return new MailConfigure(path);
    }

    public static MailConfigure defConfigure()
    {
        return MailConfigure.configurer();
    }

    public static int send(MailConfigure configure, Mail mail)
    {
        return send(configure, mail, null);
    }

    public static int send(MailConfigure configure, Mail mail, Consumer<Map<String,Object>> aftersent){
        Map<String,Object> map = new HashMap<>();
        try
        {
            // 呢称
            String nick=javax.mail.internet.MimeUtility.encodeText(mail.getNick());
            // 创建Session
            Session session =  Session.getInstance(configure.getMailProperties(), configure.getAuthenticator());

            MimeMessage message = new MimeMessage(session);

            // 设置发信人
            message.setFrom(new InternetAddress(nick + "<" + mail.getSender() +">"));

            // 接收人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getReceiver()));

            // 主题
            message.setSubject(mail.getSubject());

            // 邮件信息
            message.setContent(mail.getContent(), "text/html;charset=utf-8");

            Transport.send(message);
        }
        catch (Exception ex){
            if(aftersent != null){
                map.put("SUCCESS",0);
                map.put("EXCEPTION", ex);
                aftersent.accept(map);
            }
            return 0;
        }
        if(aftersent != null){
            map.put("SUCCESS",1);
            aftersent.accept(map);
        }
        return 1;
    }

}
